<template>
    <el-card>
      <div slot="header" class="clearfix">
        <span>
          <my-breadcrumb>素材管理</my-breadcrumb>
        </span>
      </div>
        <div style="padding: 10px 0;">
         <el-radio-group v-model="isCollect" size="medium" @change="hToggle">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
         <el-button
         @click="dialogVisible=true"
         type="success" size="mini" style="float:right">上传图片素材</el-button>
      </div>
      <!-- 素材列表 -->
      <el-row :gutter="10">
        <el-col  class="img_item" :span="4" v-for="item in images " :key="item.id">
          <el-image
            style="height: 220px;width: 220px"
              :src="item.url"
            fit="cover"
          ></el-image>
          <div class="option" v-show="!isCollect">
            <span class="el-icon-star-off" :class="{red:item.is_collected}"  @click="hSwitchCollect(item)"></span>
            <span class="el-icon-delete" @click="hDelete(item.id)"></span>
          </div>
        </el-col>
      </el-row>
      <!-- /素材列表 -->
      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        @current-change="hPageChange"
        :total="paging.total_count">
      </el-pagination>
      <!-- 分页 -->
<el-dialog
      append-to-body
      title="上传素材"
      :visible.sync="dialogVisible">
<!--
- action： 必选参数，上传的地址：http://ttapi.research.itcast.cn/mp/v1_0/user/images
- headers: 设置上传的请求头部。要携带token
- name：上传的文件字段名。要与接口中要求保持一致。
- show-file-list： 是否显示已上传文件列表
- on-success：文件上传成功时的钩子。`function(response, file, fileList)`
- before-upload: 上传之前对文件进行检测。 -->
      <el-upload
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        :headers="headers"
        name="image"
        :show-file-list="false"
        :before-upload="hBeforeUpload"
        :on-success="hUploadSuccess"
        >
        <!-- img用来显示上传成功之后的图像 -->
        <img v-if="imageUrl" :src="imageUrl" class="avatar" @load="hpreviewImageload">
        <!-- 显示引导用户上传的 那个 + 号 -->
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>

      </el-upload>
    </el-dialog>
</el-card>
</template>

<script>
export default {
  data () {
    return {
      images: [], // 照片的数据
      isCollect: false,
      paging: {
        curPage: 1, // 当前查询第几页
        total_count: 0 // 查询的总数量
      },
      dialogVisible: false,
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      imageUrl: '' // 图片的预览地址。当上传成传会从后端返回的结果取出
    }
  },
  created () {
    this.loadImages()
  },
  methods: {
    // 发送请求获取数据
    async loadImages () {
      try {
        const res = await this.$http({
          url: '/mp/v1_0/user/images',
          method: 'get',
          params: {
            page: this.paging.curPage,
            per_page: 10, // 一页的数据
            collect: this.isCollect // 收藏的图片
          }
        })
        // 将空数组里存放真实数据
        this.images = res.data.data.results
        this.paging.total_count = res.data.data.total_count
      } catch (err) {
        console.log(err)
        this.$message.error('获取失败了')
      }
    },
    // 点击换页功能
    hPageChange (page) {
      this.paging.curPage = page
      this.loadImages()
    },
    hToggle () {
      this.paging.curPage = 1
      this.loadImages()
    },
    // 上传成功
    hUploadSuccess (res, file) {
      this.imageUrl = res.data.url
      this.loadImages()
    },
    hBeforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      // file.size 单位是字节
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 删除图像
    async doDelete (id) {
      try {
        const res = await this.$http({
          url: '/mp/v1_0/user/images/' + id,
          method: 'DELETE'
        })
        this.$message.success('操作成功')
        // 更新页面
        console.log(res)
        // 发请求更新
        this.loadImages()
      } catch (err) {
        console.log(err)
        this.$message.error('操作失败')
      }
    },
    hDelete (id) {
      this.$confirm('你真的删除吗?').then(() => {
        this.doDelete(id)
      }).catch(() => {
      })
    },
    // 切换是否收藏的状态
    async hSwitchCollect (image) {
      // image是当前用户选中收藏与否 时， 所操作那张图
      const imageId = image.id
      console.log(image)
      try {
        // 调用接口，传递参数
        const res = await this.$http({
          url: '/mp/v1_0/user/images/' + imageId,
          method: 'PUT',
          data: {
            // false-取消收藏，true-添加收藏
            collect: !image.is_collected
          }
        })
        console.log(res)
        this.$message.success('操作成功')
        image.is_collected = !image.is_collected
      } catch (err) {
        console.log(err)
        this.$message.error('操作失败')
      }
    },
    hpreviewImageload () {
      // 表示图片预览成功
      console.log('图片预览成功', Date.now())
      setTimeout(() => {
        this.dialogVisible = false
        this.imageUrl = ''
      }, 2000)
    }
  }
}
</script>

<style lang="less">
  .img_item {
    position: relative;
    box-sizing: border-box;
    margin-bottom: 10px;
  }
  .option {
    position: absolute;
    left: 5px;
    width:220px;
    bottom: 5px;
    height: 35px;
    line-height: 30px;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
    color: #fff;
    span {
      margin: 0 30px;
      cursor: pointer;
    }
  }

  .avatar-uploader {
    text-align: center;
  }
  .avatar{
    width: 300px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  // TODO: 明天讲
  .avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .red {
    color: red;
  }
</style>
